import { allGet } from '@/services/pc';
import { useEffect, useRef, useState } from 'react';
import Pagination from '@/pages/pc/components/Pagination';
import { WorksItem } from '@/pages/pc/components/Works';
import styles from './index.less';
import { useHistory, Helmet } from 'umi';
import { message } from 'antd';
import type { WorkDetailModalRef } from '@/pages/pc/components/WorkDetailModal';
import WorkDetailModal from '@/pages/pc/components/WorkDetailModal';

const Works = ({ uid }) => {
  const pageSize = 18;
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const workDetailModalRef = useRef<WorkDetailModalRef>(null);
  const [loading, setLoading] = useState(true);

  const handleWorksItemClick = (index, e) => {
    workDetailModalRef.current?.show({
      ids: data.map((item) => item.bid),
      currentId: data[index]?.bid,
    });
    // VideoPlayerModal.showStar({
    //   data:
    //     props?.works?.data?.list?.map((item) => ({ ...item, url: item.video || item.pic })) || [],
    //   defaultIndex: index,
    // });
  };
  const getData = async () => {
    const params: any = {
      mod: 'busywork',
      do: 'list',
      uid,
      perpage: pageSize,
      page: currentPage,
      version: 'pc1.0',
    };
    try {
      const response = await allGet({ params });
      if (response.success) {
        setData(
          response.data?.list?.map((item) => ({ ...item, type: item.videoid ? 'video' : 'img' })) ||
            [],
        );
        setTotal(response.data.count || 0);
      }
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setLoading(true);
    getData();
  }, [currentPage]);

  const handlePageChange = (page: number, pageSize: number) => {
    setCurrentPage(page);
  };
  const handleDeleteOK = (index) => {
    message.success('删除成功');
    getData();
  };
  if (loading) return false;
  return (
    <div>
      {data.length <= 0 ? (
        <div className={styles.empty}>
          <div className={styles.icon}></div>
          <div className={styles.title}>暂未发布作业</div>
        </div>
      ) : (
        <>
          <div className={styles.works}>
            <div className={styles.list}>
              {data.map((item, index) => (
                <div key={item.bid} className={styles.item}>
                  <WorksItem
                    isLink={false}
                    itemType={7}
                    index={index}
                    type={item.type}
                    {...item}
                    handleDeleteOK={handleDeleteOK}
                    onClick={handleWorksItemClick}
                  />
                </div>
              ))}
            </div>
          </div>
          {(total > pageSize || currentPage != 1) && (
            <Pagination
              className={styles.pagination}
              onChange={handlePageChange}
              total={total}
              pageSize={pageSize}
              current={currentPage}
            />
          )}
          <WorkDetailModal ref={workDetailModalRef} />
        </>
      )}
    </div>
  );
};

const Index = (props) => {
  // const [userInfo, setUserInfo] = useState({});
  const { uid } = (useHistory().location as any)?.query;
  const init = async () => {
    // const response = await allGet({ params: { mod: 'user', do: 'space', uid, version: 'pc1.0' } });
    // if (response.success) {
    //   setUserInfo(response.data)
    // }
  };
  useEffect(() => {
    init();
  }, []);
  return (
    <div className={styles.page}>
      <Helmet>
        <title>{props.title}</title>
        <meta name="title" content={props.title} />
        <meta name="keywords" content={props.keywords} />
        <meta name="description" content={props.description} />
      </Helmet>
      <div className={styles.useinfo}>
        <img src={props?.userInfo?.avatar} className={styles.avatar} alt="" />
        {props?.userInfo?.verify === 1 && <span className={styles.auth}>已实名</span>}
        <div className={styles.username}>{props?.userInfo?.username}</div>
      </div>
      <Works uid={uid} />
    </div>
  );
};
Index.getInitialProps = async ({ match, history }) => {
  const { path, params } = match;
  const { query, search } = history?.location || {};
  const { uid } = query;

  const [detail, works] = await Promise.all([
    allGet({ params: { mod: 'user', do: 'space', uid, version: 'pc1.0' } }),
    allGet({
      params: {
        mod: 'busywork',
        do: 'list',
        uid,
        perpage: 3,
        page: 1,
        version: 'pc1.0',
      },
    }),
  ]);
  const title = `${detail?.data?.username}的个人主页 - CGJOY课堂`;
  const keywords = `${detail?.data?.username},${detail?.data?.username}的个人主页`;
  const description = `${detail?.data?.username}的个人主页,${works?.data?.list
    ?.map((item) => item.classname)
    .join(',')}`;
  return {
    userInfo: detail?.data || {},
    title,
    keywords,
    description,
  };
};
export default Index;
